// pages/index/live/live.js
const { getActivityById, getActivityAgendaList, getPoster, getCollect, updateCollect, addCollect,getActivityChatList,addActivityChat } = require("../../../utils/http/api")
const { imageUrl } = require("../../../utils/http/http").dev
Page({

  /**
   * 页面的初始数据
   */
  data: {
    timeImg: imageUrl + "/time.png",
    adressImg:  imageUrl + "/adress.png",
    baomingImg: imageUrl + "/报名.png",
    askImg: imageUrl + "/ask.png",
    isSubscribed: false,
    subscribeImage:  imageUrl + "/添加订阅.png",
    subscribe: "未订阅",
    isAddSubscribed: true,
    loading: false,
    showPoster: false,
    posterUrl: '',
    activity: null,
    active: 0,
    recordList: [],
    timeStart: '', // 用于显示开始时间的时间部分  
    timeEnd: '',    // 用于显示结束时间的时间部分  
    activityId: '',
    show: false,
    value: '',
    meetList: [],
    chatList: [],
    inputValue: '', // 文本输入框的值 

  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var _this = this
    _this.setData({
      activityId: options.activityId
    })
    _this.getActivityChatList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let _this = this
    _this.getActivityById()
    _this.getActivityAgendaList()
    _this.getCollect()
    
  },
  getActivityChatList(){
    getActivityChatList(this.data.activityId).then(res => {
      console.log("会议聊天",res.rows)
      this.setData({
        chatList: res.rows
      })
    })
  },
  getCollect() {
    let _this = this
    getCollect(_this.data.activityId).then((res) => {
      console.log("订阅状态", res);
      if (res && res.rows) {  // 确保res和res.data都存在  
        if (res.total > 0) {
          _this.setData({
            collect: res.rows[0],
            isAddSubscribed: false
          });
          let isSubscribed = res.rows[0].isCollect;
          if (isSubscribed == 1) {
            _this.setData({
              isSubscribed: true,
              subscribeImage: imageUrl + "/已订阅.png",
              subscribe: "已订阅"
            });
          } else if (isSubscribed == 0) {
            _this.setData({
              isSubscribed: false,
              subscribeImage: imageUrl + "/添加订阅.png",
              subscribe: "未订阅"
            });
          }
        }
      }
    }).catch((error) => {
      console.error('请求活动详情失败:', error);
    });
  },
  toggleSubscription() {
    let _this = this;
    console.log("isSubscribed",_this.data.isSubscribed)
    if (_this.data.isSubscribed) {
      let data = {
        topicActivityCollectId: _this.data.collect.topicActivityCollectId,
        isCollect: '0',
      }
      // 取消订阅逻辑
      updateCollect(data).then(res => {
          wx.showToast({
            title: '取消订阅成功',
            icon: 'success'
          });
          _this.setData({
            isSubscribed: false,
            subscribeImage:  imageUrl + "/添加订阅.png",
            subscribe: "未订阅"
          });
        
      })
    } else {
      if (_this.data.isAddSubscribed) {
        let addData = {
          activityId: _this.data.activityId,
          isCollect: '1',
          createBy: 3
        }
        addCollect(addData).then(res => {
          if (res.code == 200) {
            // 订阅逻辑
            wx.showToast({
              title: '订阅成功',
              icon: 'success'
            });
            _this.setData({
              isSubscribed: true,
              subscribeImage:  imageUrl + "/已订阅.png",
              subscribe: "已订阅", 
            });
          }else{
            wx.showToast({
              title: '点的慢一点哦~',
              icon: 'none'
            })
          }
        })
      }else{
        let updateData = {
          topicActivityCollectId: _this.data.collect.topicActivityCollectId,
          isCollect: '1',
        }
        // 订阅逻辑
        updateCollect(updateData).then(res => {
            wx.showToast({
              title: '订阅成功',
              icon: 'success'
            });
            _this.setData({
              isSubscribed: true,
              subscribeImage: imageUrl + "/已订阅.png",
              subscribe: "已订阅",
            });
          
        })
      }
    }
  },
  showImage() {
    let _this = this;
    _this.setData({ loading: true });
    wx.showToast({
      title: '生成海报中...', // 提示的内容
      icon: 'loading', // 图标有success、error、loading、none四种
      mask: true // 显示透明蒙层 防止触摸穿透
    });
    getPoster(_this.data.activityId).then(res => {
      _this.setData({ loading: false });
      if (res) {
        console.log("海报图片", res);
        _this.setData({
          posterUrl: res.data.url,
          showPoster: true
        });
        console.log("海报图片", _this.data.posterUrl);
        wx.hideToast(); // 请求成功后关闭弹窗
      }
    }).catch(error => {
      _this.setData({ loading: false });
      wx.hideToast(); // 请求失败后关闭弹窗
      console.error("获取海报图片失败", error);
    });
  },
  onClosePoster() {
    this.setData({
      showPoster: false
    });
  },
  downloadImage() {
    const { posterUrl } = this.data;
    wx.downloadFile({
      url: posterUrl,
      success: function (res) {
        if (res.statusCode === 200) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success(result) {
              wx.showToast({
                title: '图片已保存到相册',
                icon: 'success'
              });
            },
            fail(err) {
              console.error("保存图片失败", err);
            }
          });
        }
      },
      fail(err) {
        console.error("下载图片失败", err);
      }
    });
  },
  getActivityById() {
    let _this = this;
    getActivityById(_this.data.activityId).then((res) => {
      if (res && res.data) {  // 确保res和res.data都存在  
        const activity = res.data;
        console.log("活动", activity);
        activity.xhljActivityAgendaVoList.forEach((item) => {
          // 将字符串转换为Date对象
          let startDate = new Date(item.agendaStartTime);
          let endDate = new Date(item.agendaEndTime);
          // 格式化开始时间和结束时间
          let formattedStartTime = _this.formatAMPM(startDate);
          let formattedEndTime = _this.formatAMPM(endDate);
          // 拼接结果字符串
          item.time = `${formattedStartTime} 至 ${formattedEndTime}`;
        })
        _this.setData({
          activity: activity,
          recordList: activity.xhljActivityAgendaVoList
        });
        _this.parseActivityTimes(); // 在数据加载后解析时间 
      }
    }).catch((error) => {
      console.error('请求活动详情失败:', error);
    });
  },
  // 定义一个函数来格式化时间为上午/下午
  formatAMPM(date) {
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let ampm = hours >= 12 ? '下午' : '上午';
    hours = hours % 12;
    hours = hours ? hours : 12; // 小时为0时转换为12
    let minutesStr = minutes < 10 ? '0' + minutes : minutes; // 分钟前补0
    return `${ampm}${hours}:${minutesStr}`;
  },
  getActivityAgendaList() {
    let _this = this;
    getActivityAgendaList(_this.data.activityId).then((res) => {
      console.log("会议议程res", res);
      if (res && res.rows) {  // 确保res和res.data都存在  
        const agendaList = res.rows;
        console.log("会议议程", agendaList);
        _this.setData({
          agendaList: agendaList,
        });
      }
    }).catch((error) => {
      console.error('请求活动详情失败:', error);
    });
  },

  // 解析活动时间并更新到data中  
  parseActivityTimes: function () {
    var _this = this
    let startTime = _this.getTimeOnly(_this.data.activity.activityStartTime);
    let endTime = _this.getTimeOnly(_this.data.activity.activityEndTime);
    _this.data.activity.activityStartTime = startTime
    _this.data.activity.activityEndTime = endTime
    _this.setData({
      activity: _this.data.activity
    });
  },
  // 截取时间部分的函数  
  getTimeOnly: function (dateTimeStr) {
    return dateTimeStr.split(' ')[1].split(':').slice(0, 2).join(':');
  },

  onChange(e) {
    var _this = this;
    _this.setData({
      active: e.detail.index
    });
  },

  showPopup() {
    var _this = this;
    _this.setData({ show: true });
  },

  onClose() {
    var _this = this;
    _this.setData({ show: false });
  },
  onInput: function (e) {
    var _this = this;
    _this.setData({
      inputValue: e.detail
    });
  },
  // TODO 评论数据更新
  sendComment: function () {
    var _this = this;
    console.log('发送评论:', _this.data.inputValue);

    let data = {
      createBy: 3,
      discussionContent: _this.data.inputValue,
      activityId: _this.data.activityId
    }
    // 清空输入框
    _this.setData({
      inputValue: ''
    });
    // 发布评论并刷新评论列表
    addActivityChat(data).then(res => {
      if (res.code == 200) {
        wx.showToast({
          title: '评论成功~',
          icon: 'success'
        });
        // 更新评论列表
        return getActivityChatList(_this.data.activityId);
      } 
    }).then(res => {
      console.log("会议聊天", res.rows);
      _this.setData({
        chatList: res.rows
      });
    }).catch(error => {
      wx.showToast({
        title: error.message || '请重试',
        icon: 'none'
      });
      console.error('评论失败:', error);
    });
},

  toAsk() {
    wx.navigateTo({
      url: '/pages/index/live/ask/ask',
    })
  },
  toApplication(e) {
    wx.setStorageSync('activity', e.currentTarget.dataset.item);
    wx.navigateTo({
      url: '/pages/myself/application/application',
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})